package com.yff.tuan.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yff.tuan.model.User;
import com.yff.tuan.model.WxUser;
import com.yff.tuan.service.UserService;
import com.yff.tuan.service.WxUserService;
import com.yff.tuan.util.AESUtil;
import com.yff.tuan.util.HttpsUtil;
import com.yff.tuan.util.UserInfoUtil;
import com.yff.tuan.vo.UserVo;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

@Controller
public class WXController {
	
	@Autowired
	WxUserService service;
	@Autowired
	UserService userService;
	
	/**
	 * 登录 通过js_code 获取openid及session_key
	 * 
	 * @param code
	 * @return
	 */
	@RequestMapping("/wxaccess")
	@ResponseBody
	public Object wxlogin(String code) {
		System.out.println("》》》收到请求，请求数据为[code：" + code + "]");
		Map<String, Object> map = new HashMap<String, Object>();
		// 通过code换取网页授权web_access_token
		if (code != null && !(code.equals(""))) {
			String CODE = code;
			String WebAccessToken = "";
			String openId = "";
			// 替换字符串，获得请求URL
			String token = UserInfoUtil.getWebAccess(CODE);// 通过自定义工具类组合出小程序需要的登录凭证
															// code
			System.out.println("》》》组合token为：" + token);
			// 通过https方式请求获得web_access_token并获得小程序的返回
			String response = HttpsUtil.httpsRequestToString(token, "GET", null);
			// 通过JsonObject解析小程序返回数据
			JSONObject jsonObject = JSONObject.fromObject(response);
			System.out.println("jsonObject>>>" + jsonObject);
			// 如果JasonObject或opeid为空则登录失败
			if (null != jsonObject && jsonObject.getString("openid") != null) {
				try {
					// 从jsonObject中获取sessionKey的值
					WebAccessToken = jsonObject.getString("session_key");
					// 获取openid
					openId = jsonObject.getString("openid");
					System.out.println(
							"》》》获取access_token成功[session_key:" + WebAccessToken + "---------------openid:" + openId);
					
					map.put("id_token", openId);
				} catch (JSONException e) {
					e.printStackTrace();
					WebAccessToken = null;// 获取code失败
					System.out.println("获取session_key失败");
					map.put("stauts", 0);
					map.put("msg", "登录失败");
				}
			} else {
				System.out.println("获取openid及session_key失败");
				map.put("stauts", 0);
				map.put("msg", "登录失败");
			}
		}
		return map;
	}
	
	@RequestMapping("/wxuser")
	@ResponseBody
	public Object wxUser(WxUser user) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(null != user){
			try {
				WxUser wxUser = service.find(user);
				if(null == wxUser){
					service.insert(user);
				}
				map.put("saved", true);
			} catch (Exception e) {
				e.printStackTrace();
				map.put("saved", false);
			}
		}
		return map;
	}
	
	@RequestMapping("/wxlogin")
	@ResponseBody
	public Object login(Model model,UserVo user,HttpServletRequest request,HttpServletResponse response){
		Map<String, Object> map = new HashMap<String, Object>();
		if(null != user ){
			if(StringUtils.isEmpty(user.getName()) || StringUtils.isEmpty(user.getPassword()) || StringUtils.isEmpty(user.getOpenId())) {
				map.put("code", 0);
				map.put("msg", "请输入用户名密码！");
			}
			WxUser findUser = new WxUser();
			findUser.setOpenId(user.getOpenId());
			WxUser wxUser = service.find(findUser);
			if(null == wxUser){
				map.put("code", 0);
				map.put("msg", "未获取到授权！");
			}
			
			User queryUser = new User();
			queryUser.setPassword(AESUtil.Encrypt(user.getPassword()));
			queryUser.setName(user.getName());
			User find = userService.find(queryUser);
			if(null == userService.find(queryUser)) {
				map.put("code", 0);
				map.put("msg", "用户名或密码错误！");
			}else{
				Integer count = service.countWxUser(find.getId(), wxUser.getId());
				if(null == count || count == 0){
					map.put("code", 0);
					map.put("msg", "未获取到授权！");
				}else{
					map.put("code", 1);
					map.put("userId", find.getId());
					map.put("msg", "登录成功");
				}
			}
		}else{
			map.put("code", 0);
			map.put("msg", "请输入用户名密码！");
		}
		return map;
	}
}